# 模拟QQ服务
# 1.转发消息
# 2.处理登陆
# 3.处理退出
# 4.维护历史消息，维护在线用户的连接
import socket
from collections import defaultdict
import json
import threading

# 1.维护用户连接
online_user = defaultdict(dict)

# 2.维护用户的历史消息
user_mag = defaultdict(list)

server = socket.socket()
# 绑定ip
server.bind(("0.0.0.0",8000))
server.listen()

def handle_sock(sock,addr):

    while True:
        data = sock.recv(1024)
        json_data = json.loads(data.decode("utf8"))
        action = json_data.get("action","")
        if action == "login":
            online_user[json_data["user"]] = sock
            sock.send("登陆成功".encode("utf8"))
        elif action == "list.user":
            # 获取当前在线用户
            all_user = [user for user,sock in online_user.items()]
            sock.send(json.dumps(all_user).encode("utf8"))
        elif action == "history_msg":
            if json_data["user"] in action:
                sock.send(json.dumps(user_mag[json_data["user"],[]]).encode("utf8"))
        elif action == "send_msg":
            online_user.get(json_data["to"],None).send(json.dumps(json_data).encode("utf8"))
            user_mag[json_data["to"]].append(json_data)
        elif action == "exit":
            del online_user[json_data["user"]]
            sock.send("退出成功".encode("utf8"))


while True:
    # 阻塞等待连接
    socket, addr = server.accept()
    # 启动线程，处理新的用户连接
    client_thread = threading.Thread(target=handle_sock(),args=(socket,addr))
    client_thread.start()

# 1.多线程去处理每个用户连接，防止主线程阻塞
# 2.自定义消息协议并自己完成消息